<template>
  <vue-draggable-resizable
    :w="dragStyles.w"
    :h="dragStyles.h"
    :min-width="360"
    :min-height="300"
    :max-width="1900"
    :max-height="1000"
    :parent="false"
    :active="true"
    :x="dragStyles.x"
    :y="dragStyles.y"
    :z="999"
    class-name="drag-data-table-panel"
    class-name-handle="my-handle-class"
    @resizing="onResize"
    @dragging="onDrag"
    v-show="showDataTable"
  >
      <div class="title">
        <span>数据</span>
        <i class="close el-icon-close" @click="closeInfoWin"></i>
        <i class="close el-icon-zoom-in" @click="showTable"></i>
      </div>
      <div class="nav">
        <!-- <span class="pos">专题 :&nbsp;</span> -->
        <el-select
          class="pos"
          style="margin-left:0px;"
          v-model="value"
          size="mini"
          placeholder="请选择"
          :popper-append-to-body="false"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <!-- <span class="pos" style="color:#606266;">单位 : ({{unit}})</span> -->
      </div>
      <div class="table-container">
        <div class="table-content">
          <div class="table-data" id="el-table-data-contain">
            <el-table
              :data="resultData.value"
              size="mini"
              highlight-current-row
              @cell-mouse-enter="handleMouseEnter"
              @cell-mouse-leave="handleMouseLeave"
              border
              :height="tableHeight"
              ref="table"
            >
              <el-table-column
                type="index"
                :show-overflow-tooltip="true"
                :index="indexMethod"
                title="序号"
                align="center"
                :render-header="labelHead"
              ></el-table-column>
              <el-table-column
                v-for="(key, index) in resultData.header"
                :key="index"
                :label="key.name"
                :prop="key.name"
                align="center"
                :show-overflow-tooltip="true"
                :render-header="labelHead"
                :cell-class-name="`aaa${index}`"
              >
                <!-- <template slot-scope="scope">
              <div
                class="cell-item"
                style="font-size:1.4rem;"
                :title="scope.row[key]"
              >{{ scope.row[key] }}</div>
                </template>-->
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
  </vue-draggable-resizable>
</template>

<script>
import { constants } from "crypto";
import { mapState, mapMutations, mapActions } from "vuex";
import sgisMapBase from "@/utils/map/sfgis.map.base.js";
export default {
  name: "data-table",
  data() {
    return {
      options: [],
      value: "",
      isResize: false,
      resultData: {
        key: [],
        value: [],
        id: "",
        header:[]
      },
      tableHeight:"200px",
      tableWidth:'330',
      resultTableChangeData: [], //存放所有表格的数据便于切换
      regionCodes: [],
      unit: "",
      unitMap: config.analystUnitMap,
      // left: document.documentElement.clientWidth - 410,
      // top: 150,
      currenHover: "",
      idenData: null,
      dragStyles:{
        x: document.documentElement.clientWidth - 410,
        y: 200,
        w:360,
        h:300
      }
    };
  },
  computed: {
    ...mapState({
      showDataTable: state => state.macro.showDataTable,
      currQuotaMetaData: state => state.macro.currQuotaMetaData,
      regionCodeArray: state => state.macro.regionCodeArray,
      currQuotaGroups: state => state.macro.currQuotaGroups,
      idenCode: state => state.macro.idenCode,
      periodType: state => state.macro.periodType,
      currentIdens: state => state.macro.currentIdens,
      startTime: state => state.macro.startTime,
      currentYearMonth: state => state.macro.currentYearMonth,
      yearMonthList: state => state.macro.yearMonthList,
      currentRegionXY: state => state.macro.currentRegionXY
    })
  },
  mounted() {
    this.initEvent();
  },
  beforeDestroy() {
    EventBus.$off("formateTableData-spatialAnalysis");
    EventBus.$off("table-actiontrigger");
    EventBus.$off("table-heighLightOff");
    EventBus.$off("iden-change");
    EventBus.$off("iden-change-table");
    EventBus.$off("formateChangeCurrentData-spatialAnalysis");
    EventBus.$off("fullScreen");
  },
  created() {},
  watch: {
    value(now, old) {
      this.resultData = [];
      this.resultTableChangeData.map(item => {
        if (item.idenCode == now) {
          this.resultData = item;
          EventBus.$emit("iden-change", item.idenCode);
          EventBus.$emit("iden-change-iden-data", {
            id: item.id,
            idenData: this.idenData
          });
        }
      });
      this.setTableHeaderWidth();
    },
    showDataTable(val, oldVal) {}
  },
  methods: {
    ...mapMutations(["changeShowDataTable"]),
    onDrag(x, y, width, height){
      this.dragStyles.x = x;
      this.dragStyles.y = y;
    },
    //设置表头宽度
    setTableHeaderWidth(){
      let that = this;
      let tableWidth = 0;
      let keyArr = [];
      this.resultData.key.map(item=>{
        let width = (item.length+2)*16;
        this.resultData.value.map(ite=>{
          if(ite[item]){
            let iteWidth = (ite[item].length+2)*16;
            if(iteWidth> width){
            width = iteWidth;
            }
          }
        })
        let  newwidth = width.toString();
        tableWidth +=  Number(newwidth)
        keyArr.push({
          name:item,
          width:newwidth
        })
      })
      this.resultData.header = keyArr;
    },
    initEvent() {
      EventBus.$on("formateTableData-spatialAnalysis", this.formateTableData);
      EventBus.$on("table-actiontrigger", this.tableActionTrigger);
      EventBus.$on("table-heighLightOff", this.offHeightlightTable);
      EventBus.$on("iden-change", this.getNewIden);
      EventBus.$on("iden-change-table", this.getLayerData);
      EventBus.$on(
        "formateChangeCurrentData-spatialAnalysis",
        this.changeFormateData
      );
      EventBus.$on("fullScreen", () => {
        this.resetDragStyles();
      });
    },
    resetDragStyles(){
      let left = document.documentElement.clientWidth - 410;
      $(".drag-data-table-panel").css({"width":"360px","height":"300px","left":left,"top":"200px"})

      this.dragStyles.x = left;
      this.dragStyles.y = 200;
      this.dragStyles.w = 360;
      this.dragStyles.h = 300;
      this.tableHeight = "183px";
    },
    onResize(x, y, width, height) {
      this.dragStyles.x = x;
      this.dragStyles.y = y;
      this.dragStyles.w = width;
      this.dragStyles.h = height;
      this.tableHeight = height - 117 + "px";
    },
    showTable() {
      this.$store.commit("changeEnlargeTable", true);
      this.$store.commit("changeEnlargeChart", false);
      this.$store.commit("changeShowMapControl", false);
      this.$store.commit("changeShowDataTable", false);
      this.$store.commit("changeShowEchartPanel", false);
      this.$store.commit("changePlay", false);
    },
    getLayerData(data) {
      this.value = data.idenData;
      this.idenData = data.idenData;
    },
    getNewIden(data) {
      this.value = data;
    },
    labelHead(h, { column, $index }) {
      let l = column.label.length + 2;
      let f = 16;
      column.minWidth = f * l;
      this.$refs["table"].doLayout();
      return h("div", [column.label]);
    },
    formateTableData(data) {
      if (data) {
        document.getElementById("el-table-data-contain").style.width = "100%";
        this.options = [];
        this.resultTableChangeData = [];
        this.currentIdens.map(item => {
          this.options.push({
            value: item.idenCode,
            label: item.idenName
          });
          let objKey = ["区划"];
          let objVal = [];
          this.regionCodeArray.map(region => {
            let key = `${region}-${item.idenCode}-${region}-${this.periodType}-${item.idenCode}-${region}-${this.currentYearMonth}`;
            if (data.formateData.formatValue[key]) {
              let current_value = {};
              let currentRegionData = data.formateData.formatValue[key];
              if (item.idenCode == currentRegionData.iden_code) {
                objKey.push(currentRegionData.iden_name_hierarchical);
                current_value[currentRegionData.iden_name_hierarchical] =
                  currentRegionData.value;
                current_value["区划"] =
                  currentRegionData.ident_name_hierarchical;
                current_value["region_code"] = currentRegionData.region_code;
                this.currQuotaGroups.map(group => {
                  if (item.id == group.id) {
                    if (group.data.length) {
                      group.data.map(groupIdenVal => {
                        let currentGroupVal =
                          data.formateData.formatValue[
                            `${region}-${item.idenCode}-${groupIdenVal}-${this.periodType}-${item.idenCode}-${groupIdenVal}-${this.currentYearMonth}`
                          ];
                        if (currentGroupVal) {
                          objKey.push(currentGroupVal.ident_name_hierarchical);
                          current_value[
                            currentGroupVal.ident_name_hierarchical
                          ] =
                            currentGroupVal.value == "null"
                              ? "-"
                              : currentGroupVal.value;
                        }
                      });
                    }
                  }
                });
              }
              objVal.push(current_value);
            }
          });
          this.resultTableChangeData.push({
            idenCode: item.idenCode,
            key: Array.from(new Set(objKey)),
            // value: objVal.sort((this.compare(item.idenName)))
            value: objVal
          });
        });
        if (this.value) {
          this.value = this.currentIdens[0].idenCode;
          EventBus.$emit("formateTableData-spatialAnalysis0", data);
          this.resultTableChangeData.map(item => {
            if (item.idenCode == this.value) {
              this.resultData = item;
              this.setTableHeaderWidth();
              EventBus.$emit("iden-change", item.idenCode);
            }
          });
        } else {
          this.value = this.currentIdens[0].idenCode;
          EventBus.$emit("formateTableData-spatialAnalysis0", data);
        }
        this.$store.commit("changeShowDataTable", true);
      } else {
        this.$store.commit("changeShowDataTable", false);
      }
    },
    changeFormateData(data) {
      if (data) {
        document.getElementById("el-table-data-contain").style.width = "100%";
        this.options = [];
        this.resultTableChangeData = [];
        this.currentIdens.map(item => {
          this.options.push({
            value: item.idenCode,
            label: item.idenName
          });
          let objKey = ["区划"];
          let objVal = [];
          this.regionCodeArray.map(region => {
            let key = `${region}-${item.idenCode}-${region}-${this.periodType}-${item.idenCode}-${region}-${this.currentYearMonth}`;
            if (data.formateData.formatValue[key]) {
              let current_value = {};
              let currentRegionData = data.formateData.formatValue[key];
              if (item.idenCode == currentRegionData.iden_code) {
                objKey.push(currentRegionData.iden_name_hierarchical);
                current_value[currentRegionData.iden_name_hierarchical] =
                  (currentRegionData.value=="null"||currentRegionData.value==null)?"-":currentRegionData.value;
                current_value["区划"] =
                  currentRegionData.ident_name_hierarchical;
                current_value["region_code"] = currentRegionData.region_code;
                this.currQuotaGroups.map(group => {
                  if (item.id == group.id) {
                    if (group.data.length) {
                      group.data.map(groupIdenVal => {
                        let currentGroupVal =
                          data.formateData.formatValue[
                            `${region}-${item.idenCode}-${groupIdenVal}-${this.periodType}-${item.idenCode}-${groupIdenVal}-${this.currentYearMonth}`
                          ];
                        if (currentGroupVal) {
                          objKey.push(currentGroupVal.ident_name_hierarchical);
                          current_value[
                            currentGroupVal.ident_name_hierarchical
                          ] =
                            currentGroupVal.value == "null"
                              ? "-"
                              : currentGroupVal.value;
                        }
                      });
                    }
                  }
                });
              }
              objVal.push(current_value);
            }
          });
          this.resultTableChangeData.push({
            idenCode: item.idenCode,
            key: Array.from(new Set(objKey)),
            // value: objVal.sort((this.compare(item.idenName)))
            value: objVal
          });
        });
        if (this.value) {
          EventBus.$emit("formateTableData-spatialAnalysis0", data);
          this.resultTableChangeData.map(item => {
            if (item.idenCode == this.value) {
              this.resultData = item;
              this.setTableHeaderWidth();
              EventBus.$emit("iden-change", item.idenCode);
            }
          });
        } else {
          this.value = this.currentIdens[0].idenCode;
          EventBus.$emit("formateTableData-spatialAnalysis0", data);
        }
        this.$store.commit("changeShowDataTable", this.showDataTable);
      } else {
        this.$store.commit("changeShowDataTable", false);
      }
    },
    closeInfoWin() {
      this.changeShowDataTable(!this.showDataTable);
    },
    // compare(property) {
    //   return function(a, b) {
    //     var value1 = a[property];
    //     var value2 = b[property];
    //     return Number(value2) - Number(value1);
    //   };
    // },
    indexMethod(index) {
      return index + 1;
    },
    tableActionTrigger(data) {
      if (this.$refs.table) {
        let regionName = data.regionCode;
        let tableData = this.$refs.table.data;
        let index = 0;
        this.regionCodeArray.map((item, i) => {
          if (item == data.regionCode) {
            index = i;
          }
        });
        let hoverRow = tableData[index];
        //当前格子>5说明格子是在滚动条下:
        //5:当前表格内可以看到的行数  3-144 测试滚动
        //36行高
        if (++index > 4) {
          this.$refs.table.bodyWrapper.scrollTop = (index - 3) * 36;
        } else {
          this.$refs.table.bodyWrapper.scrollTop = 0;
        }
        this.$refs.table.setCurrentRow(hoverRow);
      }
    },
    offHeightlightTable(data) {
      if (this.$refs.table) {
        this.$refs.table.setCurrentRow();
      }
    },
    handleMouseEnter(row, column, cell, event) {
      const map = sgisMapBase.getMap();
      let index = 0;
      this.regionCodeArray.map((item, i) => {
        if (item == row.region_code) {
          index = i;
        }
      });
      this.currentRegionXY.map((item, i) => {
        if (item.code == row.region_code) {
          EventBus.$emit("onLayer-action", {
            regionCode: row.region_code,
            data: item
          });
        }
      });
      EventBus.$emit("onChart-action", { regionCode: row.region_code });
    },
    handleMouseLeave(row, column, cell, event) {
      let index = 0;
      this.regionCodeArray.map((item, i) => {
        if (item == row.region_code) {
          index = i;
        }
      });
      const map = sgisMapBase.getMap();
      if (map.overlayers["themerange"]) {
        map.overlayers["themerange"].removeCurrentData();
      }
      EventBus.$emit("off-range-themerange", { regionCode: row.region_code });
      EventBus.$emit("offChart-action", { regionCode: row.region_code });
    },
    mousedown(e) {
      if (e.srcElement.className == "title") {
        document.onmousemove = e2 => {
          this.left = e2.clientX - e.offsetX;
          this.top = e2.clientY - e.offsetY;
        };
        document.onmouseup = () => {
          document.onmousemove = null;
          document.onmousedown = null;
        };
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
@import "../css/rule.scss";
.table-container {
  box-sizing: border-box;
  padding: 10px;
  flex: 1;
}
.drag-data-table-panel {
  position: absolute;
  top: 250px;
  /*right: 46px;*/
  width: 360px;
  height: 300px;
  font-size: 1.4rem;
  z-index: 900;
  background: $panelContentBg;
  -webkit-box-shadow: 2px 5px 5px rgba(0, 0, 0, 0.3);
  box-shadow: 2px 5px 5px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  .title {
    height: 35px;
    background: $panelTitleBg;
    font-size: 1.6rem;
    color: $fontColorW;
    cursor: move;
    span {
      float: left;
      line-height: 35px;
      margin-left: 15px;
      font-weight: bold;
    }
    .close {
      float: right;
      line-height: 35px;
      margin-right: 8px;
      cursor: pointer;
      color: #fff;
    }
  }
  .el-table {
    max-width: inherit;
    width: inherit;
    min-width: 100%;
  }
  .nav {
    height: 45px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    box-sizing: border-box;
    padding: 0 10px;
    .pos {
      float: left;
      line-height: 45px;
    }
  }
  .table-content {
    height: 100%;
    width: 100%;
    overflow-x: auto;
    overflow-y: auto;
    position: relative;
    .table-data {
      position: absolute;
      min-width: 100%;
    }
  }
}
</style>
<style rel="stylesheet/scss" lang="scss" >
@import "../css/rule.scss";
.el-table--striped .el-table__body tr.el-table__row--striped.current-row td,
.el-table__body tr.current-row > td,
.el-table__body tr.hover-row.current-row > td,
.el-table__body tr.hover-row.el-table__row--striped.current-row > td,
.el-table__body tr.hover-row.el-table__row--striped > td,
.el-table__body tr.hover-row > td {
  background-color: rgba(255, 138, 61, 0.7);
  color: $fontColorW;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: rgba(255, 138, 61, 0.7);
  color: $fontColorW;
}
.table-head {
  font-size: 1.4rem !important;
  line-height: 25px !important;
  display: flex !important;
}
::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 10px;
}
::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px;
  background-color: #107089 !important;
  /* background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%, transparent 75%, transparent); */
}
::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #ffffff;
}
#mapTable {
  .el-table__header,
  .el-table__body {
    width: 100% !important;
    table-layout: auto !important;
  }
}
.drag-data-table-panel {
  .el-input--mini .el-input__inner {
    background: #17809a !important;
    color: rgba(255, 255, 255, 0.6);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
  .el-table th,
  .el-table td,
  .el-table--striped .el-table__body tr.el-table__row--striped td {
    background: rgba(23, 128, 154, 0.8);
    color: rgba(255, 255, 255, 0.6);
  }
  .el-table {
    background-color: transparent;
  }
  .el-table th,
  .el-table tr {
    background-color: transparent;
  }
  .el-table td,
  .el-table th.is-leaf,
  .el-table--border,
  .el-table--group {
    border-color: rgba(255, 255, 255, 0.1);
  }
  .el-table--border::after,
  .el-table--group::after,
  .el-table::before {
    background-color: rgba(255, 255, 255, 0.1);
  }
  .el-table__empty-text {
    color: rgba(255, 255, 255, 0.6);
  }
}

.el-select-dropdown {
  background-color: rgba(23, 128, 154, 0.8);
  border-color: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.6);
}
.el-popper[x-placement^="bottom"] .popper__arrow::after {
  border-bottom-color: rgba(23, 128, 154, 0.8);
  top: 0;
  // border-color: rgba(23,128,154,0.8);
}
.el-select-dropdown__item {
  color: rgba(255, 255, 255, 0.6);
}
.el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
  background-color: rgba(255, 138, 61, 0.7);
}
.el-select-dropdown__item.selected {
  color: #fff;
}
.my-handle-class {
  width: 10px;
  height: 10px;
  background: transparent;
  position: absolute;
}
.my-handle-class-tl {
  z-index: 999;
  cursor: nw-resize;
}
.my-handle-class-tm {
  width: 100%;
  cursor: n-resize;
}
.my-handle-class-tr {
  top: 0;
  right: 0;
  z-index: 999;
  cursor: ne-resize;
}
.my-handle-class-mr {
  height: 100%;
  right: 0;
  cursor: e-resize;
}
.my-handle-class-br {
  bottom: 0;
  right: 0;
  z-index: 999;
  cursor: se-resize;
}
.my-handle-class-bm {
  bottom: 0;
  width: 100%;
  cursor: s-resize;
}
.my-handle-class-bl {
  bottom: 0;
  left: 0;
  z-index: 999;
  cursor: sw-resize;
}
.my-handle-class-ml {
  height: 100%;
  cursor: e-resize;
}
</style>
